package com.shirley.dbExample.service.impl;

import com.shirley.dbExample.service.CrudService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * 这里偷懒，没有对每个service写实现类，而是同意写了CRUD的操作
 *
 * @param <T>  实体类：{@link com.shirley.dbExample.entity.SubCompany SubCompany}, {@link com.shirley.dbExample.entity.Salary Salary} or {@link com.shirley.dbExample.entity.Employee Employee}
 * @param <ID> 实体类主键ID类型
 */
@Slf4j
public class CrudServiceImpl<T, ID> implements CrudService<T, ID> {

    private JpaRepository<T, ID> crudRepository;

    public CrudServiceImpl(JpaRepository<T, ID> crudRepository) {
        this.crudRepository = crudRepository;
    }

    @Override
    public T save(T entity) {
        return crudRepository.save(entity);
    }

    /***
     * crudRepository.saveAll(entity); is a transactional operation even if there is no @Transactional annotation.
     *
     * 即使没有 @Transactional，当saveAll()出现异常时，SQL也会回滚
     * @param entity
     * @return
     */
    @Override
    public List<T> saveAll(List<T> entity) {
        return crudRepository.saveAll(entity);
    }

    @Override
    public T find(ID id) {
        return crudRepository.findById(id).orElse(null);
    }

    @Override
    public void delete(ID id) {
        crudRepository.deleteById(id);
    }

    @Override
    public Page<T> findPage(int page, int size) {
        return crudRepository.findAll(PageRequest.of(page, size));
    }

}
